/*
 * JSFConsole - Lightweight JSF Application Monitor
 * Copyright (C) 2009  Grzegorz Bugaj
 * http://www.gregbugaj.com
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/
package com.gregbugaj.jsfconsole.console;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.activation.MimetypesFileTypeMap;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.gregbugaj.jsfconsole.util.JarUtil;
/**
 * Phase listener responsible for displaying the console to the user
 * @author devil
 *
 */
@SuppressWarnings("serial")
public class ConsolePhaseListener implements PhaseListener {
	private static final String RESOURCE_PREFIX = "/jsfdump/jsfconsole";

	
	public void afterPhase(PhaseEvent event) {

	}

	
	public void beforePhase(PhaseEvent event) {		
		if(event.getPhaseId() != PhaseId.RENDER_RESPONSE){
			return;
		}
		FacesContext context=event.getFacesContext();
		ExternalContext externalContext=context.getExternalContext();
		//ServletContext servletContext = (ServletContext) externalContext.getContext(); 	
		String rootId=context.getViewRoot().getViewId();		
		//String contextRoot=context.getExternalContext().getRequestContextPath();
		Map<String, String> requestMap =context.getExternalContext().getRequestParameterMap();


		if(!rootId.startsWith(RESOURCE_PREFIX)){
			return; 
		}
		ServletOutputStream sos = null;

		try {
			HttpServletResponse response = (HttpServletResponse)externalContext.getResponse();
			response.setCharacterEncoding("UTF-8");
			response.setStatus(HttpServletResponse.SC_OK);

			InputStream stream=JarUtil.getStreamFromJar("/META-INF/console-web/index.html");

			sos = response.getOutputStream();
			if(stream!=null){
				response.setStatus(HttpServletResponse.SC_OK);
				//Resolve mime type, required that we have activation.jar loaded
				//Additional mime types can be defined in /META-INF/mimes.types  {@link http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/activation/MimetypesFileTypeMap.html }
				String contentType = new MimetypesFileTypeMap().getContentType("index.html");
				response.setContentType(contentType);
				byte[] buffer= new byte[1024];
				for (int bytesRead = 0; (bytesRead = stream.read(buffer, 0, buffer.length)) > 0;)
				{
					sos.write(buffer, 0, bytesRead);
				}
			}else{
				//Resource not found
				response.setStatus(HttpServletResponse.SC_NOT_FOUND);
				response.setContentType("text/html");
			}
			sos.flush();
			sos.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(sos!=null){
					sos.flush();
					sos.close();
				}
			} catch (IOException e) {
				//Suppressed
			}
			context.responseComplete();
		}
	}

	
	public PhaseId getPhaseId() {
		return PhaseId.ANY_PHASE;
	}
}
